//
//  OwnerSendMsgViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/2/8.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "ShortOwnerSendMsgViewController.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "GTMBase64.h"
#import "MyReleaseListViewController.h"

@interface ShortOwnerSendMsgViewController ()<BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UITableViewDataSource,UITableViewDelegate>{
    NSArray *_specificationArray;
    NSArray *_typeArray;
    NSArray *_timelinessArray;
    NSDictionary *_timelinessDic;
    NSArray *_remarkArray;
    UITableView *_remarkTableView;
    NSMutableArray *_selectedArray;
    UIView *_remarkBGView;
    BMKLocationService* _locService;
    BMKGeoCodeSearch* _geocodesearch;
    NSMutableArray *_photosList;
    NSString *_photosStr;
}

@end

@implementation ShortOwnerSendMsgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _photosStr =@"";
    [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, 502)];
    _selectedArray = [[NSMutableArray alloc] initWithCapacity:10];
    _photosList = [[NSMutableArray alloc] initWithCapacity:10];

    _specificationArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SpecificationData"];
    _typeArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"TypeData"];
    if (_specificationArray.count == 0) {
        [self getSpecificationData];
    }
    if (_typeArray.count == 0) {
        [self getTypeData];
    }

    [self getTimeLiness];
    [self getRemarkData];

    [self configUI];
    
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [self startLocation];
    // Do any additional setup after loading the view from its nib.
}

- (void)configUI{
    if (_goodsDic.count > 0) {
        _specificationTextField.text = _goodsDic[@"CarSpecName"];
        _typeTextField.text = _goodsDic[@"CarTypeName"];
        _licensePlateTextField.text = _goodsDic[@"CarNo"];
        _weightTextField.text = [NSString stringWithFormat:@"%@",_goodsDic[@"CarWeight"]];
        _permanentLandTextField.text = _goodsDic[@"CommAddress"];
        _textView.text = [_goodsDic[@"Remark"] isEqual:[NSNull null]]?@"":_goodsDic[@"Remark"];
        _nowLocationTextField.text = _goodsDic[@"CurrentPosition"];
        _timelinessDic = @{@"Code":_goodsDic[@"EndNum"]};
        //拍照
        float width = 35;
        float height = 35;
        float origX = 0;
        float origY = (_ImgsScroll.frame.size.height-height)/2.0;
        float gapX = 13;
        for (int i=0; i<[_goodsDic[@"Affix"] count]; i++) {
//            NSArray *array = [_goodsDic[@"Affix"][i][@"FileName"] componentsSeparatedByString:@"/"];
//            if (_photosStr.length == 0) {
//                _photosStr = [array lastObject];
//            }else{
//                _photosStr = [NSString stringWithFormat:@"%@,%@",_photosStr,[array lastObject]];
//            }
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(origX+(gapX+width)*i, origY, width, height)];
            // 下载图片
            NSString *path = [_goodsDic[@"Affix"][i][@"FileName"] stringByReplacingOccurrencesOfString:@"~" withString:@""];
            NSString *url = [NSString stringWithFormat:@"%@%@",URL_ROOT_PIC,path];
            [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil];
            imageView.layer.masksToBounds = YES;
            imageView.layer.cornerRadius = 3.0;
            
            // 事件监听
            imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)]];
            // 内容模式
            imageView.clipsToBounds = YES;
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            [_ImgsScroll addSubview:imageView];
        }
        [_cameraBtn setFrame:CGRectMake(origX+(gapX+width)*[_goodsDic[@"Affix"] count] +5, _cameraBtn.frame.origin.y, _cameraBtn.frame.size.width, _cameraBtn.frame.size.height)];
        _ImgsScroll.contentSize = CGSizeMake([_goodsDic[@"Affix"] count] >= 4 ? origX+(gapX+width)*[_goodsDic[@"Affix"] count]:origX+(gapX+width)*[_goodsDic[@"Affix"] count]+45, _ImgsScroll.frame.size.height);
    }
    
    _specificationTextField.inputAccessoryView = _doneToolBar;
    _specificationTextField.inputView = _dataPicker;
    _typeTextField.inputAccessoryView = _doneToolBar;
    _typeTextField.inputView = _typeDataPicker;
    _timelinessTextField.inputAccessoryView = _doneToolBar;
    _timelinessTextField.inputView = _dateDataPicker;
    
    [_remarkBGImg setImage:[[UIImage imageNamed:@"remark.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8,8,8,8)]];
    //可选项
    _remarkBGView = [[UIView alloc] initWithFrame:self.view.bounds];
    [_remarkBGView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_remarkBGView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:_remarkBGView.bounds];
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setAlpha:0.5];
    [_remarkBGView addSubview:bgView];
    
    _remarkTableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 300)];
    [_remarkTableView setDelegate:self];
    [_remarkTableView setDataSource:self];
    [_remarkBGView addSubview:_remarkTableView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _remarkTableView.frame.size.width , 25)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 3, 200, 16)];
    label.text = @"可选项";
    label.textColor = RGB(0, 30, 255);
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(15, 24, headView.frame.size.width, 1)];
    [line setBackgroundColor:RGB(0, 30, 255)];
    [headView addSubview:line];
    [headView addSubview:label];
    [_remarkTableView setTableHeaderView:headView];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [sureBtn setFrame:CGRectMake(15, 10, _remarkTableView.frame.size.width-30, 30)];
    [sureBtn setTitle:@"完成" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(selectRemarkData) forControlEvents:UIControlEventTouchUpInside];
    [_remarkTableView setTableFooterView:sureBtn];
    
    [_remarkBGView setHidden:YES];
    if ([[GlobalData sharedGlobalData] userinfoDic] != nil) {
        UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 70, self.navView.frame.size.height-38, 60, 30)];
        [rightBtn setTitle:@"已发布" forState:UIControlStateNormal];
        [rightBtn setBackgroundImage:[UIImage imageNamed:@"back_n.png"] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(gotoPutOut) forControlEvents:UIControlEventTouchUpInside];
        [self.navView addSubview:rightBtn];
    }
}

- (void)gotoPutOut
{
    MyReleaseListViewController *vc = [[MyReleaseListViewController alloc] initWithNibName:nil bundle:nil];
    vc.navStr = @"已发布的车源";
    vc.isOwner = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)startLocation{
    //启动LocationService
    [_locService startUserLocationService];
}

#pragma mark -请求数据
- (void)getRemarkData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/carremark",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSLog(@"responseObject=%@",responseObject);
                                  _remarkArray = responseObject;
                                  [_remarkTableView setFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, _remarkArray.count * 30 + 70)];
                                  [_remarkTableView reloadData];
                                  
                                  [SVProgressHUD dismiss];
                                  
                              }];
}

- (void)getSpecificationData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/carspec",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSMutableArray *temp = [[NSMutableArray alloc] init];
                                  [temp addObject:@{@"Code":@"0",@"CodeID":@"0",@"CodeType":@"0",@"Text":@"不限制"}];
                                  [temp addObjectsFromArray:responseObject];
                                  _specificationArray = temp;
                                  [[NSUserDefaults standardUserDefaults] setObject:_specificationArray forKey:@"SpecificationData"];
                                  [SVProgressHUD dismiss];
                                  
                              }];
}

- (void)getTypeData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/cartype",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSMutableArray *temp = [[NSMutableArray alloc] init];
                                  [temp addObject:@{@"Code":@"0",@"CodeID":@"0",@"CodeType":@"0",@"Text":@"不限制"}];
                                  [temp addObjectsFromArray:responseObject];
                                  _typeArray = temp;
                                  [[NSUserDefaults standardUserDefaults] setObject:_typeArray forKey:@"TypeData"];
                                  [SVProgressHUD dismiss];
                                  
                              }];
}

- (void)getTimeLiness{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];

    NSMutableDictionary *parameters = [GlobalData paramterDic];
  
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/carhour",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"carhour"];
                                  _timelinessArray = responseObject;
                                  [SVProgressHUD dismiss];
                                  
                              }];
}

- (void)getGoodsSendMsg{
    
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    NSString *uid = [[GlobalData sharedGlobalData] userinfoDic][@"UserID"];
    [parameters addEntriesFromDictionary:@{@"userid":uid,
                                           @"car_spec":_specificationTextField.text,
                                           @"car_type":_typeTextField.text,
                                           @"car_no":_licensePlateTextField.text,
                                           @"car_weight":_weightTextField.text,
                                           @"comm_address":_permanentLandTextField.text,
                                           @"dong_jing":[NSString stringWithFormat:@"%f", [[GlobalData sharedGlobalData] uselocation].longitude],
                                           @"bei_wei":[NSString stringWithFormat:@"%f", [[GlobalData sharedGlobalData] uselocation].latitude],
                                           @"line_type":@"0",//线路类型 0=短驳 、1=长途、2=特种
                                           @"end_num":_timelinessDic[@"Code"],
                                           @"remark":_textView.text,
                                           @"current_position":_nowLocationTextField.text,
                                           @"goods_pic":_photosStr
                                           }];
    NSString *url = [NSString stringWithFormat:@"%@car/new",URL_ROOT];
    if (_goodsDic.count > 0) {
        url = [NSString stringWithFormat:@"%@car/up",URL_ROOT];
        [parameters addEntriesFromDictionary:@{@"car_id":_goodsDic[@"CarID"]}];
    }
    [[BaseNetwork alloc] initWithMethodUrl:url
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [SVProgressHUD dismiss];
                                  
                                  if (responseObject[@"result"] == 0) {
                                      [SVProgressHUD showInfoWithStatus:@"发布失败"];
                                  }else{
                                      [SVProgressHUD showInfoWithStatus:@"发布成功"];
                                      [self backBtnAct:nil];
                                  }
                              }];
}

- (void)sendImage{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:10];
    for (int i=0 ; i < [_photosList count]; i++) {
        NSMutableDictionary *parameters = [GlobalData paramterDic];
        UIImage *img =_photosList[i];
        NSData *data = UIImageJPEGRepresentation(img, 1);
        NSString *imageStr = [GTMBase64 stringByEncodingData:data];
        [parameters addEntriesFromDictionary:@{@"byte_str":imageStr,
                                               @"img_type":@"car",
                                               }];
        [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/upfile",URL_ROOT]
                                        params:parameters
                                   requestMode:DGHTTPMethodPOST
                                   loadingShow:YES
                                  didFinshLoad:^(id result) {
                                      id responseObject = result;
                                      [list addObject:responseObject[@"result"]];
                                      if (_photosStr.length == 0) {
                                          _photosStr =responseObject[@"result"];
                                      }else{
                                          _photosStr = [NSString stringWithFormat:@"%@@%@",_photosStr,responseObject[@"result"]];
                                      }
                                      if (list.count == _photosList.count) {
                                          [self getGoodsSendMsg];
                                      }
                                  }];
        
        
    }
}

#pragma mark -IBAction
- (IBAction)selectRemarkData{
    NSString *remarkStr = nil;
    for (NSString *str in _selectedArray) {
        if (remarkStr != nil) {
            remarkStr = [NSString stringWithFormat:@"%@ %@",remarkStr,str];
        }else
            remarkStr =str;
    }
    _textView.text = remarkStr;
    [_remarkBGView setHidden:YES];
}

- (IBAction)clickRemarkData{
    [_remarkBGView setHidden:NO];
}

- (IBAction)doneSelect:(id)sender {
    if ([_specificationTextField isFirstResponder]) {
        _specificationTextField.text = [_specificationArray objectAtIndex:[_dataPicker selectedRowInComponent:0]][@"Text"];
        [_specificationTextField resignFirstResponder];
    }
    if ([_typeTextField isFirstResponder]) {
        _typeTextField.text = [_typeArray objectAtIndex:[_typeDataPicker selectedRowInComponent:0]][@"Text"];
        [_typeTextField resignFirstResponder];
    }
    if ([_timelinessTextField isFirstResponder]) {
         _timelinessDic = [_timelinessArray objectAtIndex:[_dateDataPicker selectedRowInComponent:0]];
         _timelinessTextField.text = [_timelinessArray objectAtIndex:[_dateDataPicker selectedRowInComponent:0]][@"Text"];
        [_timelinessTextField resignFirstResponder];
    }
    
}

- (IBAction)clickGoodsSendMsg:(id)sender{
    if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
        [SVProgressHUD showInfoWithStatus:@"请先登录"];
    }
    else if (_licensePlateTextField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请填写车牌号"];
    }
    else if (_weightTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写载重"];
    }
    else if (_nowLocationTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写当前位置"];
    }
    else if (_permanentLandTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写常驻位置"];
    }
    else if (_timelinessTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写时效"];
    }
    else{
        if (_photosList.count > 0) {
            [self sendImage];
        }else{
            [self getGoodsSendMsg];
        }
    }
}

- (IBAction)clearGoodsSendMsg:(id)sender{
    _licensePlateTextField.text = nil;
    _weightTextField.text = nil;
    _specificationTextField.text = nil;
    _typeTextField.text = nil;
    _nowLocationTextField.text = nil;
    _permanentLandTextField.text = nil;
    _timelinessTextField.text = nil;
}


#pragma mark -点击图片
- (IBAction)headerBtnAct:(id)sender {
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择",@"取消", nil];
    }
    else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"取消", nil];
    }
    
    [sheet showInView:self.view withCompletionHandler:^(NSInteger buttonIndex) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 1:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    // 取消
                    return;
            }
        }
        else {
            if (buttonIndex != 0) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.delegate = self;
        
        imagePickerController.allowsEditing = NO;
        
        imagePickerController.sourceType = sourceType;
        
        [(UINavigationController *)self.view.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{}];
        
    }];
    
    
    [sheet showInView:[(UINavigationController *)self.view.window.rootViewController view]];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    image = [self useImage:image];
    
    [_photosList addObject:image];
    [self paretoImgs];
//    _headData = [UIImageJPEGRepresentation(image, 0.5) retain];
//    _headImg.image = image;
}

- (UIImage *)useImage:(UIImage *)image {
    //    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // Create a graphics image context
    CGSize newSize = CGSizeMake(200, 200);
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    
    //    [pool release];
    return newImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


- (void)paretoImgs{
    //拍照
    float width = 35;
    float height = 35;
    float origX = 0;
    float origY = (_ImgsScroll.frame.size.height-height)/2.0;
    float gapX = 13;
    for (int i=0; i<[_photosList count]; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(origX+(gapX+width)*i, origY, width, height)];
        imageView.image =_photosList[i];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 3.0;

        // 事件监听
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)]];
        // 内容模式
        imageView.clipsToBounds = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [_ImgsScroll addSubview:imageView];

    }
    if (_photosList.count >= 4) {
        [_cameraBtn setHidden:YES];
    }else{
        [_cameraBtn setHidden:NO];
    }
    [_cameraBtn setFrame:CGRectMake(origX+(gapX+width)*[_photosList count] +5, _cameraBtn.frame.origin.y, _cameraBtn.frame.size.width, _cameraBtn.frame.size.height)];
    _ImgsScroll.contentSize = CGSizeMake(_photosList.count >= 4 ? origX+(gapX+width)*[_photosList count]:origX+(gapX+width)*[_photosList count]+45, _ImgsScroll.frame.size.height);
}

- (void)tapImage:(UITapGestureRecognizer *)tap {
    NSArray *imgurlArray = _photosList;
    
    int count = _photosList.count;
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        // 替换为中等尺寸图片
//        NSString *url = imgurlArray[i];
        MJPhoto *photo = [[MJPhoto alloc] init];
//        photo.placeholder = [_photosList objectAtIndex:i];
//        photo.url = [NSURL URLWithString:url]; // 图片路径
        UIImageView *imageview = [[UIImageView alloc] initWithImage:[_photosList objectAtIndex:i]];
//        [imageview sizeToFit];
        photo.srcImageView = imageview; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = (tap.view.tag>=100)?(tap.view.tag-100):tap.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}
#pragma mark -
#pragma mark loction
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_locService stopUserLocationService];
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);

    [[GlobalData sharedGlobalData] setUselocation:userLocation.location.coordinate];

    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }

}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}


-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        _nowLocationTextField.text = result.address;
    }
}

#pragma mark -
#pragma mark picker methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if ([_specificationTextField isFirstResponder]) {
        return _specificationArray.count;
    }else if ([_typeTextField isFirstResponder]){
        return _typeArray.count;
    }
    return _timelinessArray.count;
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *title;
    if ([_specificationTextField isFirstResponder]) {
        title = [_specificationArray objectAtIndex:row][@"Text"];
    }else if ([_typeTextField isFirstResponder]){
        title = [_typeArray objectAtIndex:row][@"Text"];
    }else{
       title = [_timelinessArray objectAtIndex:row][@"Text"];
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
}

#pragma mark - Table View Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_remarkArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    cell.textLabel.text = _remarkArray[indexPath.row][@"Text"];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [_remarkTableView
                             cellForRowAtIndexPath: indexPath ];
    
    if (cell.accessoryType == UITableViewCellAccessoryNone){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [_selectedArray addObject:_remarkArray[indexPath.row][@"Text"]];
        
    }
    else{
        [_selectedArray removeObject:_remarkArray[indexPath.row][@"Text"]];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
}

#pragma mark -UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//    if (textField == _specificationTextField) {
//        isSpecification =YES;
//    }else{
//        isSpecification = NO;
//    }
//    return YES;
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
